package org.rexsong.sample.petstore.services;

import org.rexsong.sample.petstore.exceptions.CustomerNotValidException;
import org.rexsong.sample.petstore.exceptions.PetNotValidException;
import org.rexsong.sample.petstore.exceptions.PetStoreException;
import org.rexsong.sample.petstore.models.Customer;
import org.rexsong.sample.petstore.models.Invoice;
import org.rexsong.sample.petstore.models.Order;
import org.rexsong.sample.petstore.models.Pet;
import org.rexsong.sample.petstore.repositories.CustomerRepository;
import org.rexsong.sample.petstore.repositories.OrderRepository;
import org.rexsong.sample.petstore.repositories.PetRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class OrderServiceImp implements OrderService {

    private CustomerRepository customerRepository;
    private OrderRepository orderRepository;
    private PetRepository petRepository;

    @Autowired
    public OrderServiceImp(CustomerRepository customerRepository, OrderRepository orderRepository, PetRepository petRepository) {
        this.customerRepository = customerRepository;
        this.orderRepository = orderRepository;
        this.petRepository = petRepository;
    }

    @Override
    public void createOrder(long petId, long customerId) throws PetStoreException {
        Optional<Customer> nullableCustomer = customerRepository.findById(customerId);
        Optional<Pet> nullablePet = petRepository.findById(petId);
        if(!nullableCustomer.isPresent()) {
            throw new CustomerNotValidException(String.format("Customer ID %s not valid", customerId));
        }
        if(!nullablePet.isPresent()) {
            throw new PetNotValidException(String.format("Pet ID %s not valid", petId));
        }
        Customer customer = nullableCustomer.get();
        Pet pet = nullablePet.get();
        Order order = new Order(pet, customer);
        Invoice invoice = new Invoice(order.getPrice(), String.format("%s %s", pet.getStatus(), pet.getName()), order);
        order.setInvoice(invoice);
        orderRepository.save(order);
    }

    @Override
    public List<Order> getOrdersPriceAbove(double price) throws PetStoreException {
        if (price < 0.00) {
            throw new PetStoreException("Please provide valid price");
        }
        return orderRepository.getOrdersAbove(price);
    }
}
